package com.wehealth.three.lib_connect.device.bluetoothdevice;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.wehealth.three.lib_connect.R;
import com.wehealth.three.lib_connect.device.usbdevice.data.ParseOriginEcgData;
import com.wehealth.three.lib_connect.utils.AppGlobals;
import com.wehealth.three.lib_connect.utils.ClassicBlueUtils;
import com.wehealth.three.lib_connect.utils.PreferenceUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/****
 * desc 经典蓝牙 获取设备信息进行设备绑定
 */
public class BTBindThread extends Thread {
    //主线程交互的handler
    Handler handler;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    //解析ecg数据
    ParseOriginEcgData ecgParser24;
    //蓝牙数据交互的socket
    private BluetoothSocket socket;
    //蓝牙api
    private BluetoothDevice btDevice;
    //数据输入流
    private InputStream mmInStream;
    //数据输出流
    private OutputStream mmOutStream;
    //蓝牙连接失败
    private final int BT_CONNECT_FAILED = 997;
    //蓝牙以连接状态
    private final int BT_CONNECTED = 996;
    //蓝牙连接失败
    private final int BT_SEND_MSG_FAILED = 993;
    private final int OBTAIN_SERIAL = 980;

    public BTBindThread(BluetoothDevice device, Handler h, ParseOriginEcgData.EcgDataGetListener ecgDataGetListener) {
        ecgParser24 = new ParseOriginEcgData(ecgDataGetListener);
        ecgParser24.ecgDataParserInit();
        handler = h;
        btDevice = device;
    }

    public void stopBlueTooth() {
        try {
            btCThreadWrite(ParseOriginEcgData.packEcgDeviceStop());
            Thread.sleep(4);
            boolean readState = true;
            while (readState) {
                if (mmInStream == null) {
                    readState = false;
                } else {
                    int available = mmInStream.available();
                    byte[] cmds = new byte[available];
                    int numBytesRead = mmInStream.read(cmds);
                    if (numBytesRead <= 0) {
                        readState = false;
                    }
//                    count ++;
//                    StringUtil.writException2File("/sdcard/bindstop.txt", new Date().toGMTString()+"  count = "+count+"\n");
                    btCThreadWrite(ParseOriginEcgData.packEcgDeviceStop());
                    Thread.sleep(2);
                }
            }
            btCThreadStop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过IO流向蓝牙设备发送数据
     */
    private void btCThreadWrite(byte[] msg) {
        if (mmOutStream != null) {
            try {
                mmOutStream.write(msg);
                mmOutStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
                handler.sendEmptyMessage(BT_SEND_MSG_FAILED);
            }
        } else {
            handler.sendEmptyMessage(BT_SEND_MSG_FAILED);
        }
    }

    /**
     * 停止连接
     */
    private void btCThreadStop() {
        ecgParser24.stopInit();
        closeSocket();
    }


    @Override
    public void run() {
        super.run();
        createSocket();
        boolean connectState = false;
        int connectCount = 0;
        while (!connectState) {
            connectState = createSocketConnect();
            if (!connectState) {
                connectCount++;
            }
            if (connectCount == 20) {
                connectState = true;
            }
        }
        if (connectCount == 20) {
            Message msg = handler.obtainMessage(BT_CONNECT_FAILED);
            msg.obj = AppGlobals.INSTANCE.get().getResources().getString(R.string.bt_bind_thread_connection_failed);
            handler.sendMessage(msg);
            return;
        }
        try {
            mmInStream = socket.getInputStream();
            mmOutStream = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (socket == null || mmInStream == null) {
            Message msg = handler.obtainMessage(BT_CONNECT_FAILED);
            msg.obj = AppGlobals.INSTANCE.get().getResources().getString(R.string.bt_bind_thread_connection_failed_prompt);
            handler.sendMessage(msg);
            return;
        }
        try {
            PreferenceUtils.getInstance().setTempSerialNo("");
            handler.sendEmptyMessage(BT_CONNECTED);
            btCThreadWrite(ParseOriginEcgData.packEcgDeviceInfoCmd());
            sleep(300);
            int available = mmInStream.available();
            byte[] cmd = new byte[available];
            mmInStream.read(cmd);
            if (!ecgParser24.EcgParserCMDInfo(cmd)) {//
                Message msg = handler.obtainMessage(BT_CONNECT_FAILED);
                msg.obj = AppGlobals.INSTANCE.get().getResources().getString(R.string.bt_bind_thread_connection_failed_prompt);
                handler.sendMessage(msg);
                return;
            }
            new ClassicBlueUtils().setSocket(socket);
        } catch (Exception e) {
            e.printStackTrace();
            Message msg = handler.obtainMessage(BT_CONNECT_FAILED);
            msg.obj = AppGlobals.INSTANCE.get().getResources().getString(R.string.bt_bind_thread_connection_failed_prompt);
            handler.sendMessage(msg);
            return;
        }

        String serialNo = PreferenceUtils.getInstance().getTempSerialNo();
        if (TextUtils.isEmpty(serialNo)) {
            Message msg = handler.obtainMessage(BT_CONNECT_FAILED);
            msg.obj = AppGlobals.INSTANCE.get().getResources().getString(R.string.ble_bind_thread_cannot_get_device_info);
            handler.sendMessage(msg);
            return;
        }
        Message msg = handler.obtainMessage(OBTAIN_SERIAL);
        msg.obj = serialNo + " " + btDevice.getAddress();
        handler.sendMessage(msg);
    }

    /**
     * 创建Socket连接
     * <p>
     * true为连接成功，否则连接失败
     */
    @SuppressLint("MissingPermission")
    private boolean createSocketConnect() {
        boolean connectState = false;
        if (socket != null && !socket.isConnected()) {
            try {
                socket.connect();
                Thread.sleep(50);
                connectState = true;
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
                connectState = false;
            }
        }
        return connectState;
    }

    /**
     * 创建Socket
     */
    @SuppressLint("MissingPermission")
    private void createSocket() {
        try {
            socket = btDevice.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 关闭蓝牙Socket
     **/
    private void closeSocket() {
        if (socket != null) {
            mmInStream = null;
            mmOutStream = null;
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket = null;
    }
}
